
import {FormattedMessage,useIntl} from 'react-intl'

type ValueType = {
    id?: string;
    message?: string;
    defaultMessage?: string;
    namespace?: string;
};
type ValuesType = Record<string, any> | Array<any>;

function replacePlaceholders(str: string, placeholders: Record<string, string>): string {
    for (const key in placeholders) {
        const regex = new RegExp('\{'+key+'\}', 'g');
        str = str.replace(regex, placeholders[key]);
    }
    return str;
}
    
export const useI18n=()=>{
  return useIntl();
}
  
export const i18nErrorCode = (value: string, values?: ValuesType) => {
    let map = {};
    if (Array.isArray(values)) {
        map = values.reduce((acc, value, index) => {
            acc[index] = value;
            return acc;
        }, {});
    } else {
        map = values || {};
    }
    return replacePlaceholders(value, map);
};

export const i18n = (value: string | ValueType, values?: ValuesType) => {

    if (!value) return value;
    
    let id = (value as ValueType)?.id ?? (value as string);
    let defaultMessage = (value as ValueType)?.message || (value as ValueType)?.defaultMessage || '';
    let map = {};

    if (Array.isArray(values)) {
        map = values.reduce((acc, value, index) => {
            acc[index] = value;
            return acc;
        }, {});

    } else {
        map = values || {};
    }
   
    return (<FormattedMessage
    id={id}
    defaultMessage={defaultMessage}
    values={map}
   />)
};